package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"lottery/models"
	"lottery/services"
	"net/http"
	"strconv"
)

type AdminResultController struct {
	ServiceUser    services.UserService
	ServiceGift    services.GiftService
	ServiceCode    services.CodeService
	ServiceResult  services.ResultService
	ServiceUserday services.UserdayService
	ServiceBlackip services.BlackipService
}

// 首页获取:查询一条或者多条数据
func (adr *AdminResultController) Get(c *gin.Context) {
	// 获取参数
	giftId, _ := strconv.Atoi(c.DefaultQuery("gift_id", "0"))
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	uid, _ := strconv.Atoi(c.DefaultQuery("uid", "0"))
	size := 10 // 默认页面大小为 100
	// 数据列表构建, 总数
	var (
		total    int
		pagePrev string // 上下页码
		pageNext string
		datalist []models.LtResult
	)
	// 通过奖品id， uid 来进行搜索,  或者查找全部的数据
	if giftId > 0 {
		datalist = adr.ServiceResult.SearchByGift(giftId, page, size)
	} else if uid > 0 {
		datalist = adr.ServiceResult.SearchByUser(uid, page, size)
	} else {
		datalist = adr.ServiceResult.GetAll(page, size)
	}
	total = (page-1)*size + len(datalist)
	if len(datalist) >= size {
		// 后面还有页数
		if giftId > 0 {
			total = int(adr.ServiceResult.CountByGift(giftId))
			fmt.Println("####### ", total)
		} else if uid > 0 {
			total = int(adr.ServiceResult.CountByUser(uid))
		} else {
			total = int(adr.ServiceResult.CountAll())
		}
		pageNext = fmt.Sprintf("%d", page+1)
	}
	if page > 1 {
		pagePrev = fmt.Sprintf("%d", page-1)
	}

	c.HTML(http.StatusOK, "admin/result", gin.H{
		"Title":    "管理后台",
		"Channel":  "result",
		"GiftId":   giftId,
		"Uid":      uid,
		"Datalist": datalist,
		"Total":    total,
		"PagePrev": pagePrev,
		"PageNext": pageNext,
	})
}

// 数据的删除: 状态改为 1
func (adc *AdminResultController) GetDelete(c *gin.Context) {
	// 获取url中的id值
	id, err := strconv.Atoi(c.Query("id"))
	if err == nil {
		// 执行删除
		adc.ServiceResult.Delete(id)
	}
	// 恢复成功了，也跳转
	c.Redirect(http.StatusFound, "/admin/result")
}

// 数据恢复： 状态改为 0
func (adc *AdminResultController) GetReset(c *gin.Context) {
	// 获取路径中的id值
	id, err := strconv.Atoi(c.Query("id"))
	if err == nil { // 设置默认值为 0
		// 执行恢复
		adc.ServiceResult.Update(&models.LtResult{Id: id, SysStatus: 0}, []string{"sys_status"})
	}

	// 恢复成功了，也跳转
	c.Redirect(http.StatusFound, "/admin/result")
}

// 设置作弊
func (adc *AdminResultController) GetCheat(c *gin.Context) {
	// 获取路径中的id值
	id, err := strconv.Atoi(c.Query("id"))
	if err == nil { // 设置默认值为 2
		// 执行恢复
		adc.ServiceResult.Update(&models.LtResult{Id: id, SysStatus: 2}, []string{"sys_status"})
	}

	// 恢复成功了，也跳转
	c.Redirect(http.StatusFound, "/admin/result")
}
